<template>
  <div class="dashboard-container">
    <el-card v-if="showCustomerInfo" class="box-card mb-5">
      <el-descriptions
        :title="$t('dashboard.customerInfo')"
        direction="vertical"
        :column="customerInfoColumn"
        border
      >
        <el-descriptions-item :label="$t('dashboard.customerLogo')">
          <div v-if="customer.logo">
            <el-image style="height: 60px" :src="customer.logo" />
            <el-icon size="20" @click="openUploadDialog"><Edit /></el-icon>
          </div>
          <div v-else>
            <el-image style="height: 60px" :src="defaultlogo" />
            <el-icon size="20" @click="openUploadDialog"><Edit /></el-icon>
          </div>
        </el-descriptions-item>
        <el-descriptions-item :label="$t('dashboard.customerName')">
          {{ customer.customerName }}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('solution.name')">
          <el-tag type="success">{{ solutionOptions.get(customer.solutionId) }}</el-tag>
          <el-icon v-if="customer.solutionId == 0" size="20" @click="openSolutionDialog">
            <Edit />
          </el-icon>
        </el-descriptions-item>
        <el-descriptions-item :label="$t('dashboard.expiredStartAt')">
          {{
            customer.customerStartAt > 0
              ? dayjs(customer.customerStartAt * 1000).format("YYYY-MM-DD")
              : ""
          }}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('dashboard.expiredEndAt')">
          {{
            customer.customerEndAt > 0
              ? dayjs(customer.customerEndAt * 1000).format("YYYY-MM-DD")
              : ""
          }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <el-row v-if="showAdmintatis" :gutter="20">
      <el-col :span="8" :xs="12">
        <el-card class="box-card mb-3">
          <div class="statistic-card">
            <el-statistic :value="adminCount.totalCustomers">
              <template #title>
                <div style="display: inline-flex; align-items: center; font-size: 16px">
                  {{ $t("dashboard.totalCustomers") }}
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8" :xs="12">
        <el-card class="box-card mb-3">
          <div class="statistic-card">
            <el-statistic :value="adminCount.willExpiredCustomers">
              <template #title>
                <div style="display: inline-flex; align-items: center; font-size: 16px">
                  {{ $t("dashboard.willExpiredCustomers") }}
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8" :xs="12">
        <el-card class="box-card mb-3">
          <div class="statistic-card">
            <el-statistic :value="adminCount.totalUsers">
              <template #title>
                <div style="display: inline-flex; align-items: center; font-size: 16px">
                  {{ $t("dashboard.totalUsers") }}
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8" :xs="12">
        <el-card class="box-card mb-3">
          <div class="statistic-card">
            <el-statistic :value="adminCount.totalDevices">
              <template #title>
                <div style="display: inline-flex; align-items: center; font-size: 16px">
                  {{ $t("dashboard.totalDevices") }}
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row v-if="showDeviceStatis" :gutter="20">
      <el-col v-hasPerm="'visitor:staff'" :span="8" :xs="12">
        <el-card class="box-card mb-3">
          <div class="statistic-card">
            <el-statistic :value="staffVisitorCount['1'] + staffVisitorCount['2']">
              <template #title>
                <div style="display: inline-flex; align-items: center; font-size: 16px">
                  {{ $t("dashboard.todayVisitorCount") }}
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col v-hasPerm="'visitor:staff'" :span="8" :xs="12">
        <el-card class="box-card mb-3">
          <div class="statistic-card">
            <el-statistic :value="staffVisitorCount['1']">
              <template #title>
                <div style="display: inline-flex; align-items: center; font-size: 16px">
                  {{ $t("dashboard.realTimeVisitor") }}
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col v-hasPerm="'visitor:staff'" :span="8" :xs="12">
        <el-card class="box-card mb-3">
          <div class="statistic-card">
            <el-statistic :value="staffVisitorCount['2']">
              <template #title>
                <div style="display: inline-flex; align-items: center; font-size: 16px">
                  {{ $t("dashboard.todayLeft") }}
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>

      <el-col v-hasPerm="'device:add'" :span="8" :xs="12">
        <el-card class="box-card mb-3">
          <div class="statistic-card">
            <el-statistic :value="visitorCount['1'] + visitorCount['2']">
              <template #title>
                <div style="display: inline-flex; align-items: center; font-size: 16px">
                  {{ $t("dashboard.todayVisitorCount") }}
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col v-hasPerm="'device:add'" :span="8" :xs="12">
        <el-card class="box-card mb-3">
          <div class="statistic-card">
            <el-statistic :value="visitorCount['1']">
              <template #title>
                <div style="display: inline-flex; align-items: center; font-size: 16px">
                  {{ $t("dashboard.realTimeVisitor") }}
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col v-hasPerm="'device:add'" :span="8" :xs="12">
        <el-card class="box-card mb-3">
          <div class="statistic-card">
            <el-statistic :value="visitorCount['2']">
              <template #title>
                <div style="display: inline-flex; align-items: center; font-size: 16px">
                  {{ $t("dashboard.todayLeft") }}
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col v-hasPerm="'device:add'" :span="8" :xs="12">
        <el-card class="box-card mb-3">
          <div class="statistic-card">
            <el-statistic :value="deviceCommonCount.gateway">
              <template #title>
                <div style="display: inline-flex; align-items: center; font-size: 16px">
                  {{ $t("dashboard.gateway") }}
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col v-hasPerm="'device:add'" :span="8" :xs="12">
        <el-card class="box-card mb-3">
          <div class="statistic-card">
            <el-statistic :value="deviceCommonCount.node">
              <template #title>
                <div style="display: inline-flex; align-items: center; font-size: 16px">
                  {{ $t("dashboard.node") }}
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col v-hasPerm="'device:add'" :span="8" :xs="12">
        <el-card class="box-card mb-3">
          <div class="statistic-card">
            <el-statistic :value="deviceCommonCount.tag">
              <template #title>
                <div style="display: inline-flex; align-items: center; font-size: 16px">
                  {{ $t("dashboard.tag") }}
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col v-hasPerm="'device:add'" :span="8" :xs="12">
        <el-card class="box-card mb-3">
          <div class="statistic-card">
            <el-statistic value-style="color:red" :value="deviceExceptCount.gateway">
              <template #title>
                <div style="display: inline-flex; align-items: center; font-size: 16px">
                  {{ $t("dashboard.exceptGateway") }}
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>

      <el-col v-hasPerm="'device:add'" :span="8" :xs="12">
        <el-card class="box-card mb-5">
          <div class="statistic-card">
            <el-statistic value-style="color:red" :value="deviceExceptCount.node">
              <template #title>
                <div style="display: inline-flex; align-items: center; font-size: 16px">
                  {{ $t("dashboard.exceptNode") }}
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
      <el-col v-hasPerm="'device:add'" :span="8" :xs="12">
        <el-card class="box-card mb-3">
          <div class="statistic-card">
            <el-statistic value-style="color:red;font-size:16px" :value="deviceExceptCount.tag">
              <template #title>
                <div style="display: inline-flex; align-items: center; font-size: 16px">
                  {{ $t("dashboard.exceptTag") }}
                </div>
              </template>
            </el-statistic>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog v-model="dialog.visible" :title="$t('dashboard.uploadLogo')">
      <el-upload ref="upload" :on-change="handleFileChange" :limit="1" :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">
          {{ $t("dashboard.chooseLogo") }}
        </el-button>
        <div slot="tip" class="el-upload__tip">
          {{ $t("dashboard.logoTip") }}
        </div>
      </el-upload>
    </el-dialog>
    <el-dialog v-model="dialogSolution.visible" :title="$t('solution.name')">
      <el-steps
        v-if="customerSolutionId === 0"
        style="max-width: 600px"
        :space="200"
        :active="2"
        align-center
        finish-status="success"
      >
        <el-step :title="t('yingdao.register')" />
        <el-step :title="t('yingdao.active')" />
        <el-step :title="t('yingdao.solutionSelect')" />
        <el-step :title="t('yingdao.payment')" />
        <el-step :title="t('yingdao.complete')" />
      </el-steps>
      <div style="margin: 20px; text-align: center">
        <el-form>
          <el-radio-group v-model="customerSolutionId">
            <el-radio v-for="item in solutionOptionsArr" :value="item.id" size="large">
              {{ item.title }}
            </el-radio>
          </el-radio-group>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSolutionSubmit">
            {{ t("common.confirm") }}
          </el-button>
          <el-button @click="handleSolutionCloseDialog">{{ t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import DevicAPI from "@/api/device/index";
import VisitorAPI from "@/api/visitor/index";
import CustomerAPI, { Customer } from "@/api/customer/index";
import router from "@/router";
import UserAPI from "@/api/system/user";
import dayjs from "dayjs";
import defaultlogo from "@/assets/defaultlogo.png";
import { UploadInstance } from "element-plus";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});
const loading = ref(false);
const customerSolutionId = ref(0);
const showDeviceStatis = ref(false);
const showAdmintatis = ref(false);
const dialogSolution = reactive({
  visible: false,
});
const upload = ref<UploadInstance>();
const deviceCommonCount: { [key: string]: number } = reactive({
  gateway: 0,
  node: 0,
  tag: 0,
});

const deviceExceptCount: { [key: string]: number } = reactive({
  gateway: 0,
  node: 0,
  tag: 0,
});

const visitorCount: { [key: string]: number } = reactive({
  1: 0,
  2: 0,
});

const staffVisitorCount: { [key: string]: number } = reactive({
  1: 0,
  2: 0,
});

const adminCount = reactive({
  totalCustomers: 0,
  totalDevices: 0,
  totalUsers: 0,
  willExpiredCustomers: 0,
});

const showCustomerInfo = ref(false);

const customerInfoColumn = ref<number>(5);

const screenWidth = window.innerWidth;
if (screenWidth < 768) {
  customerInfoColumn.value = 1;
}

const customer: Customer = reactive({
  customerName: "",
  solutionId: 0,
  customerStartAt: 0,
  customerEndAt: 0,
  logo: "",
  mainRegionuq: 0,
});

const dialog = reactive({
  visible: false,
});

import SolutionAPI from "@/api/solution/index";
const solutionOptions = reactive(new Map<number, { title: string }>([]));
const solutionOptionsArr = ref<any[]>([]);

function getDevicCount() {
  DevicAPI.countDevicesByType().then((res) => {
    if (res.common != null) {
      for (const item of res.common) {
        deviceCommonCount[item.device_type] = item.total;
      }
    }
    if (res.except != null) {
      deviceExceptCount["gateway"] = res.except["gateway"];
      deviceExceptCount["node"] = res.except["node"];
      deviceExceptCount["tag"] = res.except["tag"];
    }
  });
}

function getVisitorCount() {
  VisitorAPI.countVisitorByToday().then((res) => {
    if (res != null) {
      for (const item of res) {
        visitorCount[item.status] = item.total;
      }
    }
  });
}

function getStaffVisitorCount() {
  VisitorAPI.countStaffVisitorByToday().then((res) => {
    if (res != null) {
      for (const item of res) {
        staffVisitorCount[item.status] = item.total;
      }
    }
  });
}

function getCustomerInfo() {
  CustomerAPI.getCurrentLogedUsersCustomer().then((res) => {
    customer.customerName = res.customerName;
    customer.solutionId = res.solutionId;
    customer.customerStartAt = res.customerStartAt;
    customer.customerEndAt = res.customerEndAt;
    customer.logo = res.logo;

    setTimeout(() => {
      if (showCustomerInfo.value && customer.solutionId == 0) {
        dialogSolution.visible = true;
      }
    }, 1000);
  });
}

function getProfile() {
  loading.value = true;
  UserAPI.getProfile()
    .then((res) => {
      if ([5, 10].includes(res.userType)) {
        getSolutionOptions();
        getCustomerInfo();
        showCustomerInfo.value = true;
      }
      if (res.userCustomerId > 0) {
        getDevicCount();
        getVisitorCount();
        getStaffVisitorCount();
        showDeviceStatis.value = true;
      } else {
        countAdminStatics();
        showAdmintatis.value = true;
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

function countAdminStatics() {
  UserAPI.countAdminStatics().then((res) => {
    if (res != null) {
      console.log(res);
      Object.assign(adminCount, res);
    }
  });
}

function openUploadDialog() {
  dialog.visible = true;
}

function handleFileChange(file: any) {
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = () => {
    const base64 = reader.result as string;
    customer.logo = base64;
    CustomerAPI.uploadLogo(customer).then((res) => {
      dialog.visible = false;
      upload.value!.clearFiles();
    });
  };
}

function getSolutionOptions() {
  SolutionAPI.getList({ pageNum: 1, pageSize: 1000 })
    .then((data) => {
      solutionOptionsArr.value = data.list;
      data.list.forEach((item: any) => {
        solutionOptions.set(item.id, item.title);
      });
    })
    .finally(() => {});
}

function handleSolutionSubmit() {
  if (customerSolutionId.value == 0) {
    ElMessage.error(t("common.plsChoose") + t("solution.name"));
    return;
  }
  CustomerAPI.updateCustomerSolution(customerSolutionId.value).then((res) => {
    try {
      if (res.data.code != 200) {
        ElMessage.error(t("customer.index.updateSolutionFail"));
        return;
      }
      dialogSolution.visible = false;
      getCustomerInfo();
      ElMessage.success(t("customer.index.updateSolutionSuccess"));
      router.push("/customer/orders");
    } catch (error) {
      ElMessage.error(t("customer.index.updateSolutionFail"));
    }
  });
}
function openSolutionDialog() {
  customerSolutionId.value = customer.solutionId;
  dialogSolution.visible = true;
}
function handleSolutionCloseDialog() {
  dialogSolution.visible = false;
  customerSolutionId.value = 0;
}

onMounted(() => {
  getProfile();
});
</script>

<style lang="scss" scoped>
.el-col {
  text-align: center;
}

.dashboard-container {
  position: relative;
  padding: 24px;

  .github-corner {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    border: 0;
  }
}
</style>
